package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryReq extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public QueryReq() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		String strSQL = "SELECT COUNT(*) FROM reqs";
		ResultTableSet resultTableSet = new ResultTableSet();
		String fromCall = request.getParameter("fc");
		ArrayList<ReqStruc> reqStrucs = new ArrayList<ReqStruc>();
		
		String reqId_q = request.getParameter("reqId");
		String reqSN_q = request.getParameter("reqSN");
		
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		
		int page = 1;
		int total_pages = 1;
		int count = 0;
		int limit = 6;

		if ("".equalsIgnoreCase(sidx)|| sidx==null) {
			sidx = "reqid";
		} 
		if ("".equalsIgnoreCase(sord)|| sord==null) {
			sord = "ASC";
		} else {
			page = Integer.parseInt(request.getParameter("page"));
			limit = Integer.parseInt(request.getParameter("rows"));
		}
		
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			count = rs.getInt(1);

			if (count != 0) {

				if (limit < count) {
					total_pages = (count / limit) + 1;
				}
				if ("delivery".equalsIgnoreCase(fromCall)) {
					strSQL = "SELECT t1.reqSN, t1.reqid, t1.reqdesc,t2.sysSN,t2.sysname FROM reqs t1,envsystemlist t2 WHERE t1.sysSN=t2.sysSN";
					if ( !"".equalsIgnoreCase(reqId_q) ) { strSQL += " AND reqid='"+reqId_q+"'";  }
					if ( !"".equalsIgnoreCase(reqSN_q )) { strSQL += " AND reqSN="+reqSN_q;  }
					strSQL +=  " ORDER BY "+sidx;
				} else {
					if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
						strSQL = "SELECT t1.reqSN, t1.reqid, t1.reqdesc,t2.sysSN,t2.sysname FROM reqs t1,envsystemlist t2 WHERE t1.sysSN=t2.sysSN ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
					} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.reqSN, t1.reqid, t1.reqdesc,t2.sysSN,t2.sysname FROM reqs t1,envsystemlist t2 WHERE t1.sysSN=t2.sysSN  ORDER BY "+sidx+" "+sord;
					}
				}
				ps = conn.prepareStatement(strSQL);
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();

				while (rs.next()) {
					int reqSN = rs.getInt("reqSN");
					String reqId = wid.DB2UI( rs.getString("reqid"),conn.getMetaData().getDatabaseProductName() );
					
					if ("delivery".equalsIgnoreCase(fromCall)) {
						ReqStruc reqStruc = new ReqStruc();
						reqStruc.setReqSN(reqSN);
						reqStruc.setReqId(reqId);
						reqStruc.setReqDesc( wid.DB2UI( rs.getString("reqdesc"),conn.getMetaData().getDatabaseProductName() ) );
						reqStrucs.add(reqStruc);
					} else {
						Rows row = new Rows();
						String[] cell = null;
						row.setId(reqId);
						cell = new String[4];
						cell[0] = reqId;
						cell[1] = wid.DB2UI( rs.getString("reqdesc"),conn.getMetaData().getDatabaseProductName() );
						cell[2] = String.valueOf(rs.getInt("reqSN"));
						cell[3] = wid.DB2UI( rs.getString("sysname"),conn.getMetaData().getDatabaseProductName() );
						row.setCell(cell);
						rows.add(row);
					}
				}
				resultTableSet.setRows(rows);
			} else {
				page = 0;
				total_pages = 0;
			}
			resultTableSet.setPage(String.valueOf(page));
			resultTableSet.setTotal(total_pages);
			resultTableSet.setRecords(String.valueOf(count));
			
		} catch (SQLException e) {
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch (UnsupportedEncodingException e) {
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch (Exception e) {
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}

		if ("delivery".equalsIgnoreCase(fromCall)) {
			response.getWriter().write(new Gson().toJson(reqStrucs));
		} else {
			response.getWriter().write(new Gson().toJson(resultTableSet));
		}
	}
}